package com.zheng.study.web.controller.main;

import com.zheng.study.base.utils.Identities;
import com.zheng.study.base.utils.LogUtil;
import com.zheng.study.web.controller.BaseController;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * 控制器 - 登录
 * ============================================================================
 * author : fallenpanda
 * createDate:  2016-07-29 。
 * ============================================================================
 */
@Controller
@RequestMapping(value = "/main")
public class LoginController extends BaseController {
	private static final long serialVersionUID = -8568036648513100899L;

	private static final String webLoginResult = "/main/login";

	/**
	 * 跳转到登录页面
	 */
	@RequestMapping(value = "login", method = RequestMethod.GET)
	public String login(Model model){
		model.addAttribute("colde", Identities.uuid2());
		return webLoginResult;
	}

	/**
	 * 登录失败的情况（如果登录成功会通过shiro配置跳转到首页，不会走到这个方法）
	 */
	@RequestMapping(value = "login", method = RequestMethod.POST)
	public String login(@RequestParam("username") String username, @RequestParam("password") String password, Model model){
		LogUtil.info(username + " | " + password);
		if(SecurityUtils.getSubject().isRemembered() || SecurityUtils.getSubject().isAuthenticated()){
			return "redirect:/main/index";
		}
		String exceptionClassName = (String) request.getAttribute("shiroLoginFailure");
		String error = null;
		if (UnknownAccountException.class.getName().equals(exceptionClassName)) {
			error = "账号不存在";
		} else if (IncorrectCredentialsException.class.getName().equals(exceptionClassName)) {
			error = "用户名/密码错误";
		} else if (ExcessiveAttemptsException.class.getName().equals(exceptionClassName)) {
			error = "密码输入错误超过5次，请10分钟后再试";
		} else if (AuthenticationException.class.getName().equals(exceptionClassName)) {
			error = "您的账号没有访问权限";
		} else if ("jCaptcha.error".equals(exceptionClassName)) {
			error = "验证码错误";
		} else if (DisabledAccountException.class.getName().equals(exceptionClassName)) {
			error = "账号禁用" ;
		} else if (LockedAccountException.class.getName().equals(exceptionClassName)) {
			error = "账号锁定" ;
		} else if (exceptionClassName != null) {
			error = "其他错误：" + exceptionClassName;
		}
		model.addAttribute("username",username);
		model.addAttribute("error",error);
		model.addAttribute("code", Identities.uuid2());
		return webLoginResult;
	}

	/**
	 * 注销
	 */
	@RequestMapping(value = "logout", method = RequestMethod.GET)
	public String logout() {
		return webLoginResult;
	}

}
